merge

Purpose

Merges a domain class instance back into the current persistent context and returns a new merged instance.

Examples

def b = new Book(title:"The Shining")
b = b.merge()

Description

The merge method is similar in function to the save method, but not in behaviour. The merge allows the merging of "detached" instances such as those stored in the HTTP session. Essentially, each persistent instance is associated with a persistence context. A new persistence context is created for each request. The result is objects stored in the session lose their persistent context on subsequent requests. In this case you can't simply call save as the domain class is not associated with a current context.

The merge method on the other hand allows you to merge a detached objects state back into the current session. Unlike the save method this method returns a new instance of the class representing the re-attached object. In other words you must write code like the below:

book = book.merge()

If you don't use the return value of the merge method then you still have access to the original detached instance and you will get errors such as lazy initialization exceptions.

The merge method is defined in the Hibernate documentation as follows:

Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. If the given instance is unsaved, save a copy of and return it as a newly persistent instance.

The merge method is equivalent to the Hibernate merge method.

Parameters: